package com.openlogic.common.plugins.db.api.plugin;

import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.openlogic.common.plugins.db.api.datasource.DataSourceProcessor;

/**
* @ClassName: DataSourceProcessorManager
* @Description: 数据源处理者管理器
* @author weiyongpeng
* @date 2024年11月16日 上午8:29:25
 */
public class DataSourceProcessorManager {

	private static final Logger log = LoggerFactory.getLogger(DataSourceProcessorManager.class);

	private static final Map<String, DataSourceProcessor> dataSourceProcessorMap = new ConcurrentHashMap<>();

	private static final Set<String> dataSourceTypes = new HashSet<>();
	
	public Map<String, DataSourceProcessor> getDataSourceProcessorMap() {
		return Collections.unmodifiableMap(dataSourceProcessorMap);
	}
	
	public Set<String> getDataSourceTypeSet() {
		return Collections.unmodifiableSet(dataSourceTypes);
	}

	public void installProcessor() {

		ServiceLoader.load(DataSourceProcessor.class).forEach(factory -> {
			final String name = factory.getDbType().name();

			log.info("start register processor: {}", name);
			if (dataSourceProcessorMap.containsKey(name)) {
				throw new IllegalStateException(String.format("Duplicate datasource plugins named '%s'", name));
			}
			loadDatasourceClient(factory);

			log.info("done register processor: {}", name);

		});

	}

	private void loadDatasourceClient(DataSourceProcessor processor) {
		DataSourceProcessor instance = processor.create();
		dataSourceProcessorMap.put(processor.getDbType().name(), instance);
		dataSourceTypes.add(processor.getDbType().name());
	}
}
